<!--
  统计分析主页面
  @description SOP统计分析的主页面，包含统计卡片和图表展示
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <div class="statistics-container">
    <!-- 日期范围选择 -->
    <ContentWrap class="mb-20px">
      <el-form :model="queryParams" :inline="true" label-width="80px">
        <el-form-item :label="t('sop.statistics.dateRange')" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="datetimerange"
            range-separator="-"
            :start-placeholder="t('sop.common.startTime')"
            :end-placeholder="t('sop.common.endTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshData">
            <Icon class="mr-5px" icon="ep:refresh" />
            {{ t('sop.statistics.refresh') }}
          </el-button>
          <el-button @click="exportReport" :loading="exportLoading">
            <Icon class="mr-5px" icon="ep:download" />
            {{ t('sop.statistics.exportReport') }}
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-20px">
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon total-calls">
              <Icon icon="ep:data-analysis" size="32" />
            </div>
            <div class="card-info">
              <div class="card-title">{{ t('sop.statistics.totalCalls') }}</div>
              <div class="card-value">{{ formatNumber(overviewData.totalCalls) }}</div>
              <div class="card-trend" :class="getTrendClass(overviewData.callsTrend)">
                <Icon :icon="getTrendIcon(overviewData.callsTrend)" />
                {{ Math.abs(overviewData.callsTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon success-rate">
              <Icon icon="ep:success-filled" size="32" />
            </div>
            <div class="card-info">
              <div class="card-title">{{ t('sop.statistics.successRate') }}</div>
              <div class="card-value">{{ overviewData.successRate }}%</div>
              <div class="card-trend" :class="getTrendClass(overviewData.successRateTrend)">
                <Icon :icon="getTrendIcon(overviewData.successRateTrend)" />
                {{ Math.abs(overviewData.successRateTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon avg-response">
              <Icon icon="ep:timer" size="32" />
            </div>
            <div class="card-info">
              <div class="card-title">{{ t('sop.statistics.avgResponseTime') }}</div>
              <div class="card-value">{{ overviewData.avgResponseTime }}ms</div>
              <div class="card-trend" :class="getTrendClass(-overviewData.responseTimeTrend)">
                <Icon :icon="getTrendIcon(-overviewData.responseTimeTrend)" />
                {{ Math.abs(overviewData.responseTimeTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon error-rate">
              <Icon icon="ep:warning-filled" size="32" />
            </div>
            <div class="card-info">
              <div class="card-title">{{ t('sop.statistics.errorRate') }}</div>
              <div class="card-value">{{ overviewData.errorRate }}%</div>
              <div class="card-trend" :class="getTrendClass(-overviewData.errorRateTrend)">
                <Icon :icon="getTrendIcon(-overviewData.errorRateTrend)" />
                {{ Math.abs(overviewData.errorRateTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="mb-20px">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.statistics.apiStatistics') }}</span>
            </div>
          </template>
          <ApiStatistics
            :date-range="queryParams.dateRange"
            :loading="loading"
            @loading-change="handleLoadingChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="mb-20px">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.statistics.merchantStatistics') }}</span>
            </div>
          </template>
          <MerchantStatistics
            :date-range="queryParams.dateRange"
            :loading="loading"
            @loading-change="handleLoadingChange"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="mb-20px">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.statistics.errorStatistics') }}</span>
            </div>
          </template>
          <ErrorStatistics
            :date-range="queryParams.dateRange"
            :loading="loading"
            @loading-change="handleLoadingChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { getRealtimeStatisticsApi, exportStatisticsReportApi } from '@/api/sop/statistics'
import type { StatisticsOverviewVO, StatisticsQueryReqVO } from '@/api/sop/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import ApiStatistics from './ApiStatistics.vue'
import MerchantStatistics from './MerchantStatistics.vue'
import ErrorStatistics from './ErrorStatistics.vue'

defineOptions({ name: 'SopStatistics' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(false)
const exportLoading = ref(false)

// 查询参数
const queryParams = reactive<StatisticsQueryReqVO>({
  dateRange: [
    new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
    new Date().toISOString().slice(0, 19).replace('T', ' ')
  ]
})

// 概览数据
const overviewData = ref<StatisticsOverviewVO>({
  totalCalls: 0,
  successRate: 0,
  avgResponseTime: 0,
  errorRate: 0,
  callsTrend: 0,
  successRateTrend: 0,
  responseTimeTrend: 0,
  errorRateTrend: 0
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: t('sop.statistics.today'),
    value: () => {
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      return [start, end]
    }
  },
  {
    text: t('sop.statistics.yesterday'),
    value: () => {
      const start = new Date()
      start.setDate(start.getDate() - 1)
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      end.setDate(end.getDate() - 1)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  {
    text: t('sop.statistics.last7Days'),
    value: () => {
      const start = new Date()
      start.setDate(start.getDate() - 7)
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      return [start, end]
    }
  },
  {
    text: t('sop.statistics.last30Days'),
    value: () => {
      const start = new Date()
      start.setDate(start.getDate() - 30)
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      return [start, end]
    }
  }
]

/**
 * 获取概览数据
 */
const getOverviewData = async () => {
  try {
    const data = await getRealtimeStatisticsApi({
      startTime: queryParams.dateRange[0],
      endTime: queryParams.dateRange[1]
    })
    overviewData.value = data
  } catch (error) {
    console.error('获取统计概览失败:', error)
  }
}

/**
 * 日期范围变化
 */
const handleDateChange = () => {
  refreshData()
}

/**
 * 刷新数据
 */
const refreshData = () => {
  getOverviewData()
}

/**
 * 加载状态变化
 */
const handleLoadingChange = (isLoading: boolean) => {
  loading.value = isLoading
}

/**
 * 导出报告
 */
const exportReport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportStatisticsReportApi({
      startTime: queryParams.dateRange[0],
      endTime: queryParams.dateRange[1]
    })
    message.success(t('sop.statistics.exportSuccess'))
  } catch (error) {
    console.error('导出统计报告失败:', error)
  } finally {
    exportLoading.value = false
  }
}

/**
 * 格式化数字
 */
const formatNumber = (num: number) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 获取趋势样式类
 */
const getTrendClass = (trend: number) => {
  if (trend > 0) return 'trend-up'
  if (trend < 0) return 'trend-down'
  return 'trend-flat'
}

/**
 * 获取趋势图标
 */
const getTrendIcon = (trend: number) => {
  if (trend > 0) return 'ep:caret-top'
  if (trend < 0) return 'ep:caret-bottom'
  return 'ep:minus'
}

// 页面加载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.statistics-container {
  padding: 0;
}

.mb-20px {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-icon.total-calls {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.success-rate {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.avg-response {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.error-rate {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.trend-flat {
  color: #909399;
}
</style>
